<?php

namespace App\Cache;

use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;

abstract class Cache
{
    #[Inject(Redis::class)]
    protected Redis $redis;

    protected string $primaryKey = '';

    protected string $mainKey = '__________ling_________:';

    protected int $timeout = 60 * 5;

    public function __construct()
    {
        $this->mainKey = config('app_name') . ':';
    }

    /**
     * @param string|int $key
     * @return bool
     */
    public function has(string|int $key): bool
    {
        return $this->redis->exists($this->mainKey . $this->primaryKey . $key);
    }

    /**
     * @param string|int $key
     * @return mixed
     */
    public function get(string|int $key): mixed
    {
        return unserialize($this->redis->get($this->mainKey . $this->primaryKey . $key));
    }

    /**
     * @param string|int $key
     * @param mixed $data
     */
    public function set(string|int $key, mixed $data): void
    {
        $this->redis->set($this->mainKey . $this->primaryKey . $key, serialize($data), $this->timeout);
    }

}